package initialize

import (
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
	"userop_srv/global"
	"userop_srv/model"
)

func InitMysql() {

	//自定义日志
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second,  // Slow SQL threshold
			LogLevel:                  logger.Error, // Log level
			IgnoreRecordNotFoundError: true,         // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,         // Don't include params in the SQL log
			Colorful:                  true,         // Disable color
		},
	)

	var err error
	user := global.ServerConfig.MysqlConfig.User
	password := global.ServerConfig.MysqlConfig.Password
	host := global.ServerConfig.MysqlConfig.Host
	port := global.ServerConfig.MysqlConfig.Port
	dbName := global.ServerConfig.MysqlConfig.DbName

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, dbName)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		zap.S().Panic(err)
	}
	zap.S().Info("mysql连接成功")
	err = global.DB.AutoMigrate(&model.UserFav{}, &model.LeavingMessage{}, &model.Address{})
	if err != nil {
		zap.S().Panic(err)
	}
}
